import app from './../app.js';
import config from './../config.js';
import Base_tools_class from './../core/base-tools.js';
import Base_layers_class from './../core/base-layers.js';
import GUI_tools_class from './../core/gui/gui-tools.js';
import Image_rotate_class from '../../js/modules/image/rotate.js'
import { message } from 'antd';
import Tesseract from 'tesseract.js';
import Layer_raster_class from '../modules/layer/raster.js';

class Slide_rotate_class extends Base_tools_class {
  constructor(ctx, rasterCtx) {
    super();

    this.Base_layers = new Base_layers_class();
    this.GUI_tools = new GUI_tools_class();
    this.Image_rotate_class = new Image_rotate_class()
		this.Layer_raster = new Layer_raster_class();

    this.ctx = ctx
    this.rasterCtx = rasterCtx;
    this.name = 'slide_rotate';
    this.isSlide = false;   // 是否正在滑动
		this.startPoint = {
			x: 0,
			y: 0
		}
    this.endAngle = 0;
    this.canvas_el_wrapper = document.getElementById('main_wrapper');
    this.canvas_el_main = document.getElementById('canvas_minipaint');
  }

  load() {
    var _this = this;

    //mouse events
    document.addEventListener('mousedown', function (event) {
      _this.dragStart(event);
    });
    document.addEventListener('mousemove', function (event) {
      _this.dragMove(event);
    });
    document.addEventListener('mouseup', function (event) {
      _this.dragEnd(event);
    });

    // collect touch events
    document.addEventListener('touchstart', function (event) {
      _this.dragStart(event);
    });
    document.addEventListener('touchmove', function (event) {
      _this.dragMove(event);
    });
    document.addEventListener('touchend', function (event) {
      _this.dragEnd(event);
    });
  }

  dragStart(event) {
    var _this = this;
    if (config.TOOL.name != _this.name) return;
    _this.mousedown(event);
  }

  dragMove(event) {
    var _this = this;
    if (config.TOOL.name != _this.name) return;
    _this.mousemove(event);
  }

  dragEnd(event) {
    var _this = this;
    if (config.TOOL.name != _this.name) return;
    _this.mouseup(event);
  }

  get_layer_is_image(){
    return config.layer.type == 'image'
  }

  mousedown(e) {
    var mouse = this.get_mouse_info(e);
    
		this.startPoint = {
			x: mouse.x_real_raster,
			y: mouse.y_real_raster
		}
    this.rasterCtx.save();
    this.rasterCtx.lineWidth = 4;
    this.rasterCtx.strokeStyle = '#002c8c';
    this.rasterCtx.shadowColor = 'rgba(255,255,255,.4)';
  }

  mousemove(e) {
		var mouse = this.get_mouse_info(e);

		if (!mouse.is_drag || !mouse.click_valid) return

		var startPoint = this.startPoint;
    if((Math.abs(mouse.x_real_raster - startPoint.x) > 6) || (Math.abs(mouse.y_real_raster - startPoint.y) > 6)){   // 鼠标移动超过6px时，标记为开始滑动
      this.isSlide = true
    }

    if(!this.isSlide) return
    
    this.rasterCtx.clearRect(0, 0, config.raster_width, config.raster_height);
    this.rasterCtx.beginPath()
		this.rasterCtx.arc(startPoint.x, startPoint.y, 4, 0, 2 * Math.PI);
		this.rasterCtx.moveTo(startPoint.x, startPoint.y);
		this.rasterCtx.lineTo(mouse.x_real_raster, mouse.y_real_raster);
		this.rasterCtx.arc(mouse.x_real_raster, mouse.y_real_raster, 4, 0, 2 * Math.PI);
		this.rasterCtx.stroke();
    this.endAngle = parseInt(this.get_vertical_angle(startPoint.x, startPoint.y, mouse.x_real_raster, mouse.y_real_raster));
		message.open({
			key: this.name,
			type: 'black',
			content: `倾斜${this.endAngle}°，松手后应用`,
			duration: 0
		})
  }

  mouseup(e) {
    if(!this.isSlide) return

    this.isSlide = false
    this.rasterCtx.restore();
    this.setRotate(this.endAngle)
		message.destroy(this.name)
  }

  setRotate(rotate){
    this.Image_rotate_class.rotate_handler({
      right_angle: 'Custom',
      rotate: rotate
    })
    // 旋转后将图层转为图片
    // setTimeout(()=> {
    //   this.Layer_raster.raster();
    // })

    var $numberInput = $(`.ui_number_input#angle`);
    $numberInput.uiNumberInput('set_value', rotate);
  }

  onAutoAngle(){
    function getAngleFromPoints(x1, y1, x2, y2) {
      const slope = (y2 - y1) / (x2 - x1);;
      let angleInRadians = Math.atan(slope);
      let angleInDegrees = angleInRadians * (180 / Math.PI);
  
      if (x2 < x1) {
          angleInDegrees += 180;
      }
      if (angleInDegrees < 0) {
          angleInDegrees += 360;
      }
      return angleInDegrees;
    }

    const canvas = document.getElementById('canvas_minipaint');
    var closeLoading = message.loading('正在识别倾斜度，请稍候..', 0);
    const prefix =
    process.env.NODE_ENV === 'production'
      ? '/prs/static/js/pages/tesseract'
      : '../../../src/js/tesseract';

    Tesseract.recognize(canvas, 'chi_sim', {
      langPath: prefix + '/chi_sim', // 语言包所在路径
      workerPath: prefix + '/worker.min.js', // 设置本地 worker 路径
      corePath: prefix + '/tesseract-core-simd-lstm.wasm.js', // 如果有 core 路径，可以设置
    }).then(({ data }) => {
      let block = data.blocks[0] || {};
      let baseline = block.baseline || null;

      if(!baseline) {
        closeLoading()
        message.error('倾斜度识别异常，请再次尝试');
        return
      }

      let angle = getAngleFromPoints(baseline.x0, baseline.y0, baseline.x1, baseline.y1);
      this.setRotate(360 - angle)
      
      closeLoading()
      message.success('自动纠偏完成！');
    }).catch((err) => {
      closeLoading()
      message.error('倾斜度识别异常，请再次尝试');
      console.log(err);
    });
  }

  on_params_update(data){
    this.setRotate(data.value)
  }

  on_activate(){
    if(config.layer && config.layer.rotate != 0){
      setTimeout(() => {
        this.setRotate(config.layer.rotate)
      }, 10)
    }
  }

  render(ctx, layer) {
    //nothing
  }

  // 返回坐标(x,y)相对坐标原点(originX, originY)的笛卡尔直角坐标系坐标
  get_relation_croods(x, y, originX, originY){
    return {
      x: x - originX,
      y: originY - y
    }
  }

  // 返回笛卡尔直角坐标系坐标(x,y)在Canvas二维坐标系中的坐标
  relation_croods_to_raster_croods(x, y, originX, originY){
    return {
      x: x + originX,
      y: originY - y
    }
  }

  // 获取(x,y)与坐标原点连线的角度（顺时针从Y轴正半区开始）
  get_calculate_angle(x, y){
    // 获取弧度
    let angleRad = Math.atan2(x, y);
    //  弧度转为角度
    let angleDeg = angleRad * (180 / Math.PI);
    //  360度内
    if (angleDeg < 0) angleDeg += 360;
    return angleDeg;
  }


	// 获取两点连线的垂直线与坐标原点交点的相对Y轴角度
	get_vertical_angle(x1, y1, x2, y2){
    var canvas_wrapper_rect = this.canvas_el_wrapper.getBoundingClientRect();
    var canvas_main_rect = this.canvas_el_main.getBoundingClientRect();
    var canvas_main_center = {
      x: (canvas_main_rect.x - canvas_wrapper_rect.x) + canvas_main_rect.width / 2,
      y: (canvas_main_rect.y - canvas_wrapper_rect.y) + canvas_main_rect.height / 2
    }

    // 坐标系转换
    var relation_croord_1 = this.get_relation_croods(x1, y1, canvas_main_center.x, canvas_main_center.y);
    var relation_croord_2 = this.get_relation_croods(x2, y2, canvas_main_center.x, canvas_main_center.y);

    // 连线斜率
    var m = (relation_croord_2.y - relation_croord_1.y) / (relation_croord_2.x - relation_croord_1.x);

    // 斜率为0、90、180、270直接返回角度
    if(Object.is(m, 0)) return 0
    else if(m === -Infinity) return 90
    else if(Object.is(m, -0)) return 180
    else if(m === Infinity) return 270

    var vertical_junction_x = (m * relation_croord_1.x - relation_croord_1.y) / (m + 1 / m);
    var vertical_junction_y = -vertical_junction_x / m;

    return this.get_calculate_angle(vertical_junction_x, vertical_junction_y)
	}
}
export default Slide_rotate_class;
